package k2_reflection.demo02;

import k1_jdbc.tool.ConnectionTool;
import k1_jdbc.tool.Const;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class ObjectOperation {

    public static void insertObject(Object object){

        Connection conn = null;
        PreparedStatement ps = null;

        //获取对象的Class类型
        Class objClass = object.getClass();

        //获取当前对象的类名，直接作为sql语句的表名
        String tableName = objClass.getSimpleName();
        //获取当前对象的类中所有的属性数组
        Field[] fields = objClass.getDeclaredFields();

        try {
            Class.forName(Const.DRIVER);

            conn = DriverManager.getConnection(Const.URL_TEST, Const.USERNAME, Const.PASSWORD);

            //用StringBuffer拼接sql语句
            StringBuffer sb = new StringBuffer("insert into "+tableName.toLowerCase()+" values(");

            //有多少个属性，就有多少个问号
            for (int i = 1; i <= fields.length ; i++) {
                sb.append(i==fields.length?"?)":"?,");
            }

            System.out.println(sb.toString());

            //对这个sql语句进行预处理
            ps = conn.prepareStatement(sb.toString());

            //遍历所有的属性，获取这个对象中每个属性的值，分别设置相应问号
            for (int i = 0; i < fields.length ; i++) {
                //获取数组中的第 i 个属性
                Field currentField = fields[i];
                //把所有的属性都设置为 私有 允许访问
                currentField.setAccessible(true);
                //从对象中获取相应属性的值
                Object fieldValue = currentField.get(object);
                //对相应的问号进行赋值
                ps.setObject(i+1,fieldValue);
            }

            int result = ps.executeUpdate();

            System.out.println(result);

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            ConnectionTool.closed(conn,ps);
        }
    }

    public static void main(String[] args) {

        Teachers teacher = new Teachers(100,"tom");
        Customer customers = new Customer("jerry",20,"hrb",100);


        insertObject(customers);
    }

}
